package com.usermanage.controller;

import com.usermanage.SecurityConfig.SpringSecurityUtils;
import com.usermanage.SecurityConfig.UserDetail;
import com.usermanage.Service.ProjectService;
import com.usermanage.beanParam.PermissionBean;
import com.usermanage.beanParam.ProjectBean;
import com.usermanage.util.DateUtil;
import com.usermanage.util.JsonData;
import com.usermanage.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/project")
public class ProjectController {

    @Resource
    private ProjectService projectService;

    @RequestMapping("/list.page")
    public ModelAndView indexPage() {
        ModelAndView mv = new ModelAndView();
        //获得用户登陆信息
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
        //从用户登陆信息中获取用户权限列表
        List<PermissionBean> permissionBeanList = userDetail.getList();
        //判断用户具有的权限在界面展示
        List<PermissionBean> result = new ArrayList<>();
        for (PermissionBean bean : permissionBeanList) {
            if (bean.getPermission_url().equals("/project/add.page")) {
                result.add(bean);
            }
        }
        mv.addObject("permissionList", result);
        mv.addObject("company_id", userDetail.getCompany_id());
        mv.setViewName("/project/index");
        return mv;
    }

    @RequestMapping("/list.json")
    public JsonData list(String key, String page, String limit) {
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
        List<PermissionBean> permissionBeanList = SpringSecurityUtils.getCurrentUser().getList();
        List<Map> operaButton = new ArrayList<>();
        for (PermissionBean bean : permissionBeanList) {
            if (bean.getPermission_url().equals("/project/cancel.json")) {
                Map map = new HashMap();
                map.put("name", bean.getPermission_name());
                map.put("fn", "del");
                operaButton.add(map);
            }
            if (bean.getPermission_url().equals("/project/update.page")) {
                Map map = new HashMap();
                map.put("name", bean.getPermission_name());
                map.put("fn", "modify");
                operaButton.add(map);
            }
            if (bean.getPermission_url().equals("/project/detail.page")) {
                Map map = new HashMap();
                map.put("name", bean.getPermission_name());
                map.put("fn", "detail");
                operaButton.add(map);
            }
        }

        //品宅可看到全部项目
        List<ProjectBean> list;
        int count;
        if ("1".equals(userDetail.getCompany_id())) {
            list = projectService.findAllList(key, page, limit, null);
            count = projectService.getListCount(key, null);
        } else {
            list = projectService.findAllList(key, page, limit, userDetail.getCompany_id());
            count = projectService.getListCount(key, userDetail.getCompany_id());
        }
        if (operaButton.size() == 0) {
            Map map = new HashMap();
            map.put("name", "--");
            operaButton.add(map);
        }

        Map map = new HashMap();
        map.put("operaButton", operaButton);
        map.put("list", list);
        map.put("count", count);
        return JsonData.success(map);
    }

    @RequestMapping(value = "/add.page", method = RequestMethod.GET)
    public ModelAndView add() throws Exception {
        ModelAndView mv = new ModelAndView();
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
       String company_id  = userDetail.getCompany_id();
       mv.addObject("company_id",company_id);
        mv.setViewName("/project/add");
        return mv;
    }

    @RequestMapping(value = "/projectList.json", method = RequestMethod.GET)
    public JsonData projectList(String company_id) throws Exception {
        if(StringUtils.isBlank(company_id)){
            UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
            company_id  = userDetail.getCompany_id();
        }
        List<ProjectBean> list;
        int count;
        if ("1".equals(company_id)) {
            list = projectService.findAllList(null, "0", "0", null);
            count = projectService.getListCount(null, null);
        } else {
            list = projectService.findAllList(null, "0", "0", company_id);
            count = projectService.getListCount(null, company_id);
        }
        Map map = new HashMap();
        map.put("list", list);
        map.put("count", count);
        return JsonData.success(map);
    }



    @RequestMapping(value = "/insert.json", method = RequestMethod.POST)
    public JsonData insert(ProjectBean projectBean, BindingResult bindingResult) {
        if (StringUtils.isBlank(projectBean.getProject_code()) || StringUtils.isBlank(projectBean.getProject_name())) {
            return JsonData.fail("项目名称与项目编号不能为空");
        }
        //验证提交数据是否合法
        if (bindingResult.hasErrors()) {
            return JsonData.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        boolean bool = projectService.isExisit(projectBean.getProject_code(), null);
        if (!bool) {
            String company_id = SpringSecurityUtils.getCurrentUser().getCompany_id();
            if ("1".equals(company_id)) {
                return JsonData.fail("甲方不可新增项目");
            }
            projectBean.setCompany_id(company_id);
            projectBean.setProject_status("00");
            projectBean.setProject_create_time(DateUtil.getNowTimeString());
            try {
                projectService.save(projectBean);
                return JsonData.success();
            } catch (Exception e) {
                log.error("项目添加失败：" + e.toString());
                return JsonData.fail("项目添加失败，请稍后重试");
            }
        } else {
            return JsonData.fail("该项目编号已存在");
        }
    }

    @RequestMapping(value = "/detail.page")
    public ModelAndView detailPage(String id) throws Exception {
        ModelAndView mv = new ModelAndView();
        mv.addObject("id",id);
        mv.setViewName("/project/detail");
        return mv;
    }

    @RequestMapping(value = "/detail.json")
    public JsonData detailJson(String id) {
        if (StringUtils.isBlank(id)) {
            return JsonData.fail("请选择项目");
        }
        Optional<ProjectBean> projectBean = projectService.findById(Integer.valueOf(id));
        return JsonData.success(projectBean);
    }

    @RequestMapping(value = "/update.page")
    public ModelAndView updatePage(String id) throws Exception {
        ModelAndView mv = new ModelAndView();
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
        String company_id  = userDetail.getCompany_id();
        mv.addObject("company_id",company_id);
        mv.addObject("id",id);
        mv.setViewName("/project/update");
        return mv;
    }

    @RequestMapping(value = "/update.json")
    public JsonData updateJson(ProjectBean projectBean, BindingResult bindingResult) {
        if (StringUtils.isBlank(projectBean.getProject_code()) || StringUtils.isBlank(projectBean.getProject_name())) {
            return JsonData.fail("项目名称与项目编号不能为空");
        }
        //验证提交数据是否合法
        if (bindingResult.hasErrors()) {
            return JsonData.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        boolean bool = projectService.isExisit(projectBean.getProject_code(), projectBean.getId());
        if (!bool) {
            try {
                projectService.save(projectBean);
                return JsonData.success();
            } catch (Exception e) {
                log.error("项目修改失败：" + e.toString());
                return JsonData.fail("项目修改失败，请稍后重试");
            }
        } else {
            return JsonData.fail("该项目编号已存在");
        }
    }

    @RequestMapping(value = "/cancel.json")
    public JsonData cancel(String id) {
        if (StringUtils.isBlank(id)) {
            return JsonData.fail("请选择项目");
        }
        Optional<ProjectBean> bean = projectService.findById(Integer.valueOf(id));
        bean.get().setProject_status("99");
        try {
            projectService.save(bean.get());
            return JsonData.success();
        } catch (Exception e) {
            log.error("项目作废失败：" + e.toString());
            return JsonData.fail("项目作废失败，请稍后重试");
        }
    }
}
